from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
import atom.url
import gdata.docs.service
import gdata.contacts.data
import gdata.contacts.client
import gdata.contacts.service
import gdata.alt.appengine
import settings
import cgi
from django.utils import simplejson


class Fetch(webapp.RequestHandler):
  
    def getContacts(self, query=''):
        client = gdata.contacts.service.ContactsService()
        gdata.alt.appengine.run_on_appengine(client)

        obj = {}
        data = []

        if query:
          uri = client.GetFeedUri()+"?%s" % (query)
        else:
          uri = client.GetFeedUri()

        #self.response.out.write("""getContacts: uri=%s <br>""" % (uri))

        try:
            obj['msg'] = "Success"
            feed = client.GetContactsFeed(uri)
            for e in feed.entry:
                for em in e.email:
                    if em.primary and em.primary == "true":
                        contact = {}
                        contact['name'] = e.title.text
                        contact['email'] = em.address
                        data.append(contact)
        except gdata.service.RequestError, request_error:
            data = []
            if request_error[0]['status'] == 401:
                obj['msg'] = "Need auth"
            else:
                obj['msg'] = "Something went wrong, : %s" % (
                            str(request_error[0]))

        obj['data'] = data
        jsonstr = simplejson.dumps(obj)
        self.response.out.write(jsonstr)


    #example using client api
    def getContacts2(self):
        client = gdata.contacts.client.ContactsClient()
        #gdata.alt.appengine.run_on_appengine(client)

        try:
            feed = client.GetContacts()
            for e in feed.entry:
                self.response.out.write('%s<br>' % e.name.full_name.text)
        except gdata.client.Unauthorized, e:
            self.response.out.write("Need authorization")

    #example using base gdata api
    def getContacts3(self):
        client = gdata.service.GDataService()
        gdata.alt.appengine.run_on_appengine(client)

        feed = "http://www.google.com/m8/feeds/contacts/default/full?start-index=1&max-results=100"

        try:
            response = client.Get(feed)
            for entry in response.entry:
              self.response.out.write('%s<br>' % entry.title.text)
        except gdata.service.RequestError, request_error:
            # If fetching fails, then tell the user that they need to login to
            # authorize this app by logging in at the following URL.
            if request_error[0]['status'] == 401:
                self.response.out.write('Need authorization')
            else:
                self.response.out.write('Something went wrong, : %s' % (
                        str(request_error[0])))


    def fetchDocs(self):
        client = gdata.service.GDataService()
        gdata.alt.appengine.run_on_appengine(client)

        feed = "http://docs.google.com/feeds/documents/private/full"

        try:
            response = client.Get(feed, converter=str)
            self.response.out.write(cgi.escape(response))
        except gdata.service.RequestError, request_error:
            # If fetching fails, then tell the user that they need to login to
            # authorize this app by logging in at the following URL.
            if request_error[0]['status'] == 401:
                self.response.out.write('Need authorization')
            else:
                self.response.out.write('Something went wrong, : %s' % (
                        str(request_error[0])))

    def get(self):
        #self.response.out.write("""v1 request uri: %s <br>""" % self.request.uri)
        service = self.request.get('service')
        query = self.request.get('q')
        if service == "contacts":
          #self.response.out.write("""contact service: %s %s <br>""" % (
                    #service, query))
          self.getContacts(query)
        elif service == "docs":
          self.fetchDocs()
        


def main():
    application = webapp.WSGIApplication([('/fetch', Fetch),], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
